package com.swj.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.swj.reggie.common.BaseContext;
import com.swj.reggie.common.R;
import com.swj.reggie.entity.Dish;
import com.swj.reggie.entity.SetmealDish;
import com.swj.reggie.entity.ShoppingCart;
import com.swj.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车  /shoppingCart/add  post请求
     * @param shoppingCart
     * @return shoppingCart 返回新的封装了数量和userId的数据
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        //设置用户id，指定当前是哪个用户的购物车数据
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        // userId和dishId/setmealId 两个字段能唯一定位当前用户的菜品选择信息
        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId); // select * from shopping_cart where user_id = ?
        if(dishId != null){
            //添加到购物车的是菜品    select * from shopping_cart where dish_id = ?
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else{
            //添加到购物车的是套餐    select * from shopping_cart where setmeal_id = ?
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        //查询当前菜品或者套餐是否在购物车中
        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        ShoppingCart cartServiceOne = shoppingCartService.getOne(queryWrapper);
        if(cartServiceOne == null){
            //如果不存在，则添加到购物车，数量默认就是一
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now()); // shoppingCart的createTime字段没有自动填充 @TableField(fill = FieldFill.INSERT)
            shoppingCartService.save(shoppingCart);
            cartServiceOne = shoppingCart;
        }else{
            //如果已经存在，就在原来数量基础上加一
            Integer number = cartServiceOne.getNumber();
            cartServiceOne.setNumber(number + 1);
            shoppingCartService.updateById(cartServiceOne);
        }

        return R.success(cartServiceOne);
    }

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 清空购物车，根据当前用户userId，删除shoppingCart中的相关数据
     * URL: /shoppingCart/clean  请求方法: DELETE
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        //SQL:delete from shopping_cart where user_id = ?
        shoppingCartService.remove(queryWrapper);
        return R.success("清空购物车成功");
    }

    /**
     * 减少选购数量，减少某个选择的菜品或套餐的数量
     * 请求URL:  http://localhost:8080/shoppingCart/sub
     * 请求方法:  POST
     * 请求体：   {dishId: "1413385247889891330", setmealId: null} 或者 {"setmealId":"1646115168388763650",dishId:null}
     * 1、   select * from shoppingCart where userId = ? and dishId/setmealId = ?
     * 2.1、 getNumber = 1 --> delete from shoppingCart where userId = ? and dishId/setmealId = ?
     * 2.2、 getNumber > 1 --> update shoppingCart set number=number-1 where userId = ? and dishId/setmealId = ?
     */
    @PostMapping("/sub")
    public R<String> sub(@RequestBody Map map){
        Long userID = BaseContext.getCurrentId();
        String dishId_ = (String) map.get("dishId");
        String setmealId_ = (String) map.get("setmealId");

        // 拼接查询条件   select * from shoppingCart where userId = ? and dishId/setmealId = ?
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userID);

        if (dishId_ != null){       // System.out.println(dishId_.getClass());
            long dishId = Long.parseLong(dishId_);
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else{
            Long setmealId = Long.valueOf(setmealId_);
            queryWrapper.eq(ShoppingCart::getSetmealId,setmealId);
        }
        ShoppingCart shoppingCart = shoppingCartService.getOne(queryWrapper);

        // 拿到 菜品/套餐的数量
        Integer number = shoppingCart.getNumber();
        if (number > 1) {                   // 选购数量大于1，修改数量 update
            shoppingCart.setNumber(number - 1);
            shoppingCartService.updateById(shoppingCart);   // shu
        } else {                            // 选购数量等于1，删除这行数据 delete
            shoppingCartService.removeById(shoppingCart.getId());
        }
        return R.success("减少选购数量成功");

    }
}